import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { forkJoin, from } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';

import { PutSaveService } from '../put-save/put-save.service';
import { PurchasePlanApplyService } from '../purchase-plan-apply/purchase-plan-apply.service'
import { PurchaseOrderAddService } from '../purchase-order-add/purchase-order-add.service'

@Component({
  selector: 'app-put-direct-warehousing',
  templateUrl: './put-direct-warehousing.component.html',
  styleUrls: ['./put-direct-warehousing.component.scss']
})
export class PutDirectWarehousingComponent implements OnInit {

  // 路由传参
  routeParams: any ={};

  formParams: any = {
    warehousingNumber: '', // 入库单号
    warehousing: {
      type: '', // 入库类型(1、采购入库 2、售后入库  3、不良品返厂 4、坏件入库 5、代售入库)
      whPutId: '', // 入库仓库
      firstParty: '', // 甲方
      partyB: '', // 乙方
      remark: '', // 备注
      state: 0
    },
    list: [],
    storageTotal: '' // 合计
  };
  // 保存loading
  subLoading: boolean = false;

  nzWidthConfig: string[] = ['50px','100px','250px','200px','150px','120px','150px','120px',];
  // 仓库下拉list
  warehouseLists: any = [];
  // 甲方乙方下拉list
  supplierList: any = [];
  // 入库类型集合
  storageTypeList: any = [
    { content: 3, name: '不良品返厂' },
    { content: 4, name: '坏件入库' },
    { content: 5, name: '代售入库' }
  ];
  // 入库品质
  qualityList: any = [
    { value: 'RW', text: '待返工品' },
    { value: 'QA', text: '待确认品' },
    { value: 'DM', text: '不良品' },
    { value: 'NR', text: '良品' },
  ];
  // 批量操作品质下拉选中值
  selectedQuality: any = '';

  // 已选table
  selectedTables: any = [];

  // modelTable
  isVisible: boolean = false;
  modelSeachForms: any = {
    whGood: '',
    lineupNumber: '',
    stock: '',
    oversoldNumber: ''
  }
  modelTableData: any = [1];
  modelTableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 10,
    total: 0
  };

  // modelTable****** 勾选
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = []; // 当前展示页面数据
  setOfCheckedId = new Set<number>(); // 已选ids
  setofCheckedArrs: object[] = []; // 已选项数组

  /******************************** BOM model START ********************************/
  isBomVisible: boolean = false;
  bomModelLoading: boolean =false;
  boomNumber: any = '1';
  bomActiveId: any = '';
  /******************************** BOM model END ********************************/

  constructor(
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private PutSaveService: PutSaveService,
    private PurchasePlanApplyService: PurchasePlanApplyService,
    private PurchaseOrderAddService: PurchaseOrderAddService
  ) {
    this.activatedRoute.params.subscribe((res: any) => {
      // console.log('router params', res);
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    let postArr: any = [
      this.PutSaveService.dict('inbound_type'),
      this.PutSaveService.getWhList(),
      this.PurchaseOrderAddService.getSupplierList()
    ];
    forkJoin(postArr).subscribe((list: any) => {
      // list[0,1,2]=[类型、仓库、甲乙方]
      let storageTypeArrs = list[0].data.list || [];
      let warehouseArrs = list[1];
      let supplierArrs = list[2];

      // 入库类型下拉list
      if (storageTypeArrs.records && storageTypeArrs.records.length) {
        this.storageTypeList = storageTypeArrs.records || [];
      }

      // 入库仓库下拉list
      if (warehouseArrs.code == 0 && warehouseArrs.data.records && warehouseArrs.data.records.length) {
        this.warehouseLists = warehouseArrs.data.records.filter((item: any) => { return item.state == 1 });
      }

      // 甲方乙方下拉list
      if (supplierArrs.code == 0 && supplierArrs.data.records && supplierArrs.data.records.length) {
        this.supplierList = supplierArrs.data.records.filter(function (item: any) { return item.state == 1 });
      }

      // 详情
      if (this.routeParams.id != '0') {
        this.getDetailsData(this.routeParams.id);
      }
    })
  }

  // 查询详情
  getDetailsData(id: any) {
    this.PutSaveService.details(id).subscribe((res: any) => {
      if (res.code == 0) {
        const { warehousing, list }: any = res.data || [];
        this.formParams.warehousingNumber = warehousing.warehousingNumber; // 入库单号
        this.formParams.warehousing.type = String(warehousing.type); // 入库类型
        this.formParams.warehousing.whPutId = warehousing.whPutId; // 入库仓库
        this.formParams.warehousing.firstParty = Number(warehousing.firstParty); // 甲方
        this.formParams.warehousing.partyB = Number(warehousing.partyB); // 乙方
        this.formParams.warehousing.remark = warehousing.remark; // 备注

        this.selectedTables = list || [];
        // 入库数量合计
        this.setStorageTotal();
      } else {
        this.message.error(res.message || '详情获取失败');
      }
    }, (error: any) => {
      this.message.error(error);
    })
  }

  // 添加
  addTableItems() {
    this.setOfCheckedId.clear();
    
    this.selectedTables.forEach((ele: any) => {
      this.setOfCheckedId.add(ele.whGoodsId);
    });
    this.setofCheckedArrs = JSON.parse(JSON.stringify(this.selectedTables));

    this.modelTableForms.page = 1;
    this.couponTableData()
    this.isVisible = true;
  }
  // model确定
  handleOk(): void {
    this.isVisible = false;
  }
  // model取消
  handleCancel(): void {
    this.isVisible = false;

    this.setOfCheckedId.clear();
    this.setofCheckedArrs = [];
  }
  // 删除
  deleteItems(item: any, index: number) {
    this.selectedTables.splice(index, 1);
    this.setStorageTotal();
  }

  /**********************************************model表格勾选操作 START**********************************************/
  couponTableData() {
    const params = {
      ...this.modelSeachForms,
      page: this.modelTableForms.page,
      pageSize: this.modelTableForms.pageSize
    }

    this.modelTableForms.tableLoading = true;
    this.PurchasePlanApplyService.whGetList(params).subscribe((res: any) => {
      this.modelTableForms.tableLoading = false;
      if (res.code == 0) {
        const { records, total }: any = res.data || [];

        this.modelTableData = records || [];
        this.modelTableForms.total = total || 0;
      } else {
        this.message.error(res.message || '数据获取失败');
      }
    }, (error: any) => {
      this.modelTableForms.tableLoading = false;
      this.modelTableData = [];
      this.modelTableForms.total = 0;
    })
  }

  // model搜索
  seachData() {
    this.modelTableForms.page = 1;
    this.couponTableData()
  }
  // 重置
  resetData() {
    for (let key in this.modelSeachForms) {
      this.modelSeachForms[key] = '';
    }

    this.modelTableForms.page = 1;
    this.couponTableData()
  }

  // 确认已选项
  relationData() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择商品');
      return
    }

    this.selectedTables = JSON.parse(JSON.stringify(this.setofCheckedArrs)) || [];
    this.isVisible = false;
    
    this.message.success(`已勾选 ${this.setOfCheckedId.size} 件商品`);
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.modelTableForms.page = index;
    this.couponTableData()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.modelTableForms.page = 1;
    this.modelTableForms.pageSize = sizeNum;

    this.couponTableData()
  }

  // 勾选设置
  updateCheckedSet(id: number, checked: boolean, item?: any): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      if (this.setofCheckedArrs.length > 0) {
        let isHas = this.setofCheckedArrs.some((tag: any) => { return tag.whGoodsId == id });
        if (!isHas) {
          this.setofCheckedArrs.push({...item, whGoodsId: id, state: 0});
        }
      } else {
        this.setofCheckedArrs.push({...item, whGoodsId: id, state: 0});
      }
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setofCheckedArrs.findIndex((tag: any) => { return tag.whGoodsId == id });
      this.setofCheckedArrs.splice(delIndex, 1);
    }
  }
  // 单选
  onItemChecked(id: number, checked: boolean, item?: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }
  // 全选
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }
  // 当前页面展示数据改变的回调函数
  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }
  // 全选按钮状态
  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
  /**********************************************model表格勾选操作 END**********************************************/

  // 保存
  preserData() {
    if (!this.verifData()) {
      return
    }
    
    let params = {
      warehousing: this.formParams.warehousing,
      list: JSON.parse(JSON.stringify(this.selectedTables))
    }
    this.subLoading = true;

    if (this.routeParams.id == '0') {
      params.list.map((item: any) => delete item.id);

      this.PutSaveService.save(params).subscribe((res: any) => {
        this.subLoading = false;
        this.subResult(res);
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    } else {
      params.warehousing.id = this.routeParams.id;
      
      this.PutSaveService.update(params).subscribe((res: any) => {
        this.subLoading = false;
        this.subResult(res);
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    }
  }

  // submit success
  subResult(res: any) {
    if (res && res.code == 0) {
      this.message.success('保存成功');
      this.router.navigate(['/stock/put']);
    } else {
      this.message.error(res.message || '保存失败');
    }
  }

  // 入库数量累加
  setStorageTotal() {
    this.formParams.storageTotal = 0;
    this.formParams.storageTotal = this.selectedTables.reduce((total: any, item: any) => {
      return total + (Number(item.number) || 0)
    }, 0);
  }
  // 入库数量 回车聚焦到下一个
  onKeydownEnter(ev: any, id: number) {
    const { keyCode }: any = ev;
    if (keyCode == 13) {
      document.getElementById(`putSaveInputID${id + 1}`)?.focus();
    }
  }
  // 品质批量选择
  selectQuality(val: any) {
    this.selectedTables.forEach((item: any) => {
      if (val) {
        item.quality = val;
      }
    })
  }

  // 查询BOM单list
  getBomItemData() {
    let params = {
      id: this.bomActiveId,
      boomNumber: this.boomNumber
    }
    this.PurchasePlanApplyService.getBomListData(params).subscribe((res: any) => {
      if (res.code == 0 && res.data && res.data.length) {
        res.data.forEach((item: any) => {
          // 勾选回填
          this.onItemChecked(item.id, true, item);
        });
      } else {
        this.message.error(res.message || 'bom数据获取失败');
      }

      this.relationData();
      this.setStorageTotal();
    }, (error: any) => {
      // console.log(error);
      this.message.error(error);
    })
  }
  // BOM model open
  selectBom(id: any) {
    this.bomActiveId = id;
    this.isBomVisible = true;
  }
  // BOM model 确定
  bomhandleOk(): void {
    if (!this.boomNumber) {
      this.message.warning('请先输入倍数');
      return
    }
    this.getBomItemData();
    this.isBomVisible = false;
  }
  // BOM model 取消
  bomhandleCancel(): void {
    this.isBomVisible = false;
    this.boomNumber = '1';
  }

  // 验证
  verifData() {
    if (!this.formParams.warehousing.type) {
        this.message.warning("请选择入库类型");
        return false;
    }
    if (!this.formParams.warehousing.whPutId) {
        this.message.warning("请选择入库仓库");
        return false;
    }
    if (!this.formParams.warehousing.firstParty) {
      this.message.warning("请选择甲方");
      return false;
    }
    if (!this.formParams.warehousing.partyB) {
      this.message.warning("请选择乙方");
      return false;
    }
    if (!this.selectedTables.length) {
        this.message.warning("请选择入库内容");
        return false;
    }
    
    for (let i = 0; i < this.selectedTables.length; i++) {
      const { number, quality } = this.selectedTables[i];
      if (!number) {
        this.message.warning('入库数量不能为空');
        return false;
      } else if (!quality) {
        this.message.warning('品质不能为空');
        return false;
      }
    }
    return true;
  }
}
